<template>
    <div id="RoleManage">
        <el-row  style="margin-bottom: 20px;">
            <el-col :span="1">
                <el-button type="primary" @click="addNewRole">新增角色</el-button>
            </el-col>
        </el-row>
         <el-table
            :data="roleList"
            border
            v-loading="loading"
            style="width: 100%"
            :row-class-name="tableRowClassName">
            <el-table-column
            prop="roleName"
            label="角色名称"
            width="180">
            </el-table-column>
            <el-table-column
            prop="description"
            label="描述"
            width="180">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
    </el-table-column>
        </el-table>
         <el-pagination
                background
                layout="prev, pager, next"
                :total="totalRecord"
                @current-change="currentChange">
        </el-pagination>
        <el-dialog
            title="编辑"
            :visible.sync="dialogVisible"
            width="40%"
           >
            <el-form label-width="80px">
                 <el-form-item label="角色名称">
                    <el-input style="width:180px" v-model="roleInfo.roleName"></el-input>
                    <el-switch
                        v-model="status"
                        active-text="开启"
                        inactive-text="禁用">
                    </el-switch>
                </el-form-item>
                <el-tree
                :data="showAllPermissionList"
                show-checkbox
                node-key="permissionName"
                ref="tree"
                highlight-current
                >
                </el-tree> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRoleInfo(),dialogVisible = false">确 定</el-button>
            </span>
            </el-dialog>
            <router-view></router-view>
    </div>
</template>

<script>
import qs from 'qs'
export default {

    data() {
      return {
        roleList: [],
        dialogVisible: false,
        permissionList: [], 
        defaultProps: {
            children: 'children',
            label: 'label'
        },
        searchRoleValue: '',
        allPermission: [],
        roleInfo: {},
        totalRecord: 1,
        status: '0',//禁用状态
        loading: false

      }
    },
    computed: {
        showAllPermissionList(){
            if(this.allPermission.length>0){
              var rs =  this.toTree(this.allPermission);
            }
            return rs;
        }
    },
    methods: {
        tableRowClassName({row, rowIndex}) {
            if (rowIndex === 1) {
            return 'warning-row';
            } else if (rowIndex === 3) {
            return 'success-row';
            }
            return '';
        },
        // 处理编辑
        handleEdit(index,row){
            this.dialogVisible = true;
            var roleId = row.roleId;
            var _this = this;
            this.$http.get(window.baseURL+"/backstage/role/find?roleId="+roleId+"&token="+this.$token)
            .then(function(response){
                _this.permissionList = response.data.data.permissionList;
                _this.roleInfo = response.data.data.role;
                console.log(_this.permissionList);
                // // 设置默认选项
                var checkedNode = [];
                _this.permissionList.forEach((item)=>{
                    if(item.parentId){
                        checkedNode.push(item);
                    }
                })
                _this.$refs.tree.setCheckedNodes(checkedNode);
            })
            .catch(function(){

            })
        },
        // 更新角色信息
        updateRoleInfo(){
            // 数据更新模式
                var updateURL = window.baseURL+"/backstage/role/update";
                var checkedNode = this.$refs.tree.getCheckedNodes();
                console.log(checkedNode);
                var permissionIds = '';
                for(var i=0;i<checkedNode.length;i++){
                    if(i<checkedNode.length-1){
                        permissionIds += checkedNode[i].permissionId+','+checkedNode[i].parentId+",";
                    }else{
                        permissionIds += checkedNode[i].permissionId;
                    }
                }
               permissionIds = Array.from(new Set(permissionIds.split(','))).join(',');
               console.log(permissionIds);
                var role = {roleName: this.roleInfo.roleName,
                            status: Number(this.status),
                            roleId:this.roleInfo.roleId,
                            permissionIds: permissionIds,
                            token: this.$token
                            }
                this.$http.post(updateURL,qs.stringify(role))
                .then(()=>{
                    this.loadData(1);                    
                })
                .catch(function(){

                })
                // 更新之后加载所有的数据
        },
        toTree(data) {
            // 删除 所有 children,以防止多次调用
            data.forEach(function (item) {
                delete item.children;
            });
            // 将数据存储为 以 id 为 KEY 的 map 索引数据列
            var map = {};
            data.forEach(function (item) {
                item.label = item.permissionName;
                map[item.permissionId] = item;
            });
            var val = [];
            data.forEach(function (item) {
                // 以当前遍历项，的pid,去map对象中找到索引的id
                var parent = map[item.parentId];
                // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
                if (parent) {
                    (parent.children || ( parent.children = [] )).push(item);
                } else {
                    //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                    val.push(item);
                }
            });
            return val;
        },
        currentChange(value){
            this.loadData(value);
        },
        addNewRole(){
            //新增角色
            this.$router.push({name:'AddNewRoleView'})
        },
        // 删除角色
        handleDelete(index,row){
            var action = ()=>{
                this.loading = true;
                var deleteURL = window.baseURL+"/backstage/role/delete";
                 this.$http.post(deleteURL,qs.stringify({roleId:row.roleId,token:this.$token}))
                .then((response)=>{
                    if(response.data.success){
                        var url = window.baseURL+"/backstage/role/findByPage?token="+this.$token;
                        this.loadData(1);
                        this.loading = false;
                    } 
                })
                .catch(function(error){
                    console.log(error);
                })
            }
            // 确认是否删除
            this.operatorConfirm(action,"删除角色")
            
        },
        // 加载数据
        loadData(pageNum){
            var _this = this;        
            this.$http.get(window.baseURL+'/backstage/role/findByPage?token='+this.$token+'&pageNum='+pageNum+'&pageSize=20')
            .then(function(response){
                response = response.data;
                if(response){
                    _this.roleList = response.data.list.results;  
                    _this.totalRecord = response.data.list.totalRecord;
                }
            })
            .catch(function(error){
                console.log(error);
            })
            //获取所有权限
            var allPermissionURL = window.baseURL+'/backstage/permission/findAllPermission?token='+this.$token;
            this.$http.get(allPermissionURL)
            .then(function(response){
                response = response.data;
                if(response){
                    _this.allPermission = response.data;
                }
            })
            .catch(function(error){
                console.log(error)
            })
        }
    },
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.loadData(1);
        });
    },
    beforeRouteUpdate(to,from,next){
        if(to.name =="角色管理"){
            this.loadData(1);
        }
        next();
    },
    created(){
        
    }
}
</script>

<style lang="scss" scoped>
 .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  #RoleManage {
        width: 100%;
        padding: 40px;
        box-sizing: border-box;
        position: absolute;
        #searchView {
            width: 100%;
            height: 64px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }
  }
</style>
